<template>
  <!--弹出窗-->
  <modal ref="modal_1" :title="title" :isCloseConfirm="this.editable" :fullscreen="this.fullscreen" top="3%" width="50%"
    :close-on-click-modal="true" @modalOpened="opened" @modalClose="closed">


      <avue-form :option="option" ref="form" v-model="form" @submit="onSubmit" >
      </avue-form>



    <!--底部按钮块, 默认只有"取消"按钮-->
    <template #footerButton>
      <el-button type="primary" v-if="(permission.supplier_add || permission.supplier_edit) && editable"
        :loading="btnLoading" @click="this.$refs.form.submit()">保 存
      </el-button>
      <el-button @click="$refs.modal_1.handleClose()">关闭</el-button>
    </template>
  </modal>
</template>

<script>
import { getList, getDetail, add, update, remove } from "@/api/anwise/supplier";
import { mapGetters } from "vuex";
import { getDeptTree } from '@/api/system/dept';
import website from '@/config/website';
import {Pattern} from "@/utils/validate.js";
import {userCompany} from "@/api/anwise/common";

export default {
  data() {
    return {
      emits: ["success"],
      editable: false,
      title: "银行信息",
      isCloseConfirm: false,
      fullscreen: false,
      btnLoading: false,
      form: {},
      query: {},
      loading: true,
        isRole:"",//安韦1加工商3
      option: {
        height: 'auto',
        calcHeight: 30,
        labelWidth: 150,
        menuWidth: 120,
        submitBtn: false,
        emptyBtn: false,
        column: [
            {
                label: "供应商全称",
                prop: "supName",
                type: "input",
                search: true,
                maxlength: 2000,
                rules: [{
                    required: true,
                    message: "请输入供应商全称",
                    trigger: "blur"
                }],
                change:value => this.setSupCode(value),
            },
          // {
          //   label: "供应商简称",
          //   prop: "supCode",
          //   type: "input",
          //   // search: true,
          //   maxlength: 500,
          //   rules: [{
          //     required: false,
          //     message: "请输入供应商简称",
          //     trigger: "blur"
          //   }],
          // },
          {
            label: "供应商类型",
            prop: "supType",
            type: "select",
            search: true,
              filterable: true,
              change:value => this.ownHiddenChange(value),
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=supplier_type',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            dataType: 'string',
            rules: [{
              required: true,
              message: "请输入供应商类型",
              trigger: "blur"
            }],
          },
          {
            label: "供应商地址",
            prop: "supAddr",
            type: "input",
            search: true,
            maxlength: 2000,
            rules: [{
              required: true,
              message: "请输入供应商地址",
              trigger: "blur"
            }],
          },
          {
            label: "结算方式",
            prop: "payType",
            type: "select",
            search: true,
              filterable: true,
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=pay_type',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            dataType: 'string',
            rules: [{
              required: true,
              message: "请输入结算方式",
              trigger: "blur"
            }],
          },
            {
                label: "税率",
                prop: "taxRate",
                type: "input",
                append: '%VAT',
              value:0.00,
                rules: [{
                    required: true,
                    message: "请输入税率",
                    trigger: "blur"
                },{
                    pattern: Pattern.number_3,
                    message: '请输入正确的数字',
                    trigger: 'blur',
                }],
            },
            // {
            //     label: "币别",
            //     prop: "rmb",
            //     type: "input",
            //     maxlength:50,
            //     rules: [{
            //         required: false,
            //         message: "请输入币别",
            //         trigger: "blur"
            //     }],
            // },
            {
                label: "币别",
                prop: "rmb",
                type: "select",
                filterable: true,
                dicUrl: '/api/blade-system/dict-biz/dictionary?code=rmb',
                props: {
                    label: 'dictValue',
                    value: 'dictKey',
                },
                value:'RMB',
                dataType: 'string',
                rules: [{
                    required: true,
                    message: "请选择币别",
                    trigger: "blur"
                }],
            },
          {
            label: "联系人",
            prop: "supContact",
            type: "input",
            search: true,
            maxlength: 500,
            rules: [{
              required: true,
              message: "请输入联系人",
              trigger: "blur"
            }],
          },
          {
            label: "联系电话",
            prop: "supPhone",
            type: "input",
            search: true,
            maxlength: 500,
            rules: [{
              required: true,
              message: "请输入联系电话",
              trigger: "blur"
            }],
          },
          {
            label: "邮箱地址",
            prop: "supMail",
            type: "input",
            search: true,
            maxlength: 500,
            rules: [{
              required: false,
                pattern:Pattern.email,
              message: "请输入正确的邮箱地址",
              trigger: "blur"
            }],
          },
            // {
            //     label: "组织机构",
            //     prop: "deptId",
            //     type: "select",
            //     search: true,
            //     filterable: true,
            //     dicUrl: '/api/blade-anwise/common/supplierDept',
            //     props: {
            //         label: 'deptName',
            //         value: 'id',
            //     },
            //     dataType: 'string',
            //     display:'true',
            //     change:value => this.deptIdChange(value),
            //     rules: [{
            //         required: false,
            //         message: "请输入组织机构",
            //         trigger: "blur"
            //     }],
            // },

          {
            label: "创建人员",
            prop: "createUserName",
            type: "input",
            display: false,
            disabled: true,
          },
          {
            label: "创建时间",
            prop: "createTime",
            type: "input",
            display: false,
            disabled: true,
          },
          {
            label: "是否有效",
            prop: "supStatus",
            type: "select",
              filterable: true,
              dicUrl: '/api/blade-system/dict-biz/dictionary?code=is_enabled',
              props: {
                  label: 'dictValue',
                  value: 'dictKey',
              },
              dataType: 'string',
              value:'有效',
              rules: [{
                  required: true,
                  message: "请选择是否有效",
                  trigger: "blur"
              }],
          },
            {
                label: "归属机构",
                prop: "ownId",
                type: "select",
                search: true,
                filterable: true,
                virtualize: true,
                dicUrl: '/api/blade-anwise/common/deptListFilter?deptCategory=1&bodyType=1,3',
                display:true,
                props: {
                    label: 'deptName',
                    value: 'id',
                },
                dataType: 'string',
                rules: [{
                    required: true,
                    message: "请输入归属机构",
                    trigger: "blur"
                }],
            },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.supplier_add, false),
        viewBtn: this.validData(this.permission.supplier_view, false),
        delBtn: this.validData(this.permission.supplier_delete, false),
        editBtn: this.validData(this.permission.supplier_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  mounted() {
    // 非租户模式默认加载管理组数据
    this.initData(website.tenantId);
    console.log("aaaaaaaaaa",this.$refs.modal_1)
  },
  methods: {
      ownHiddenChange(value){
          if(this.isRole === 1){
              if(value.value == "采购商"){
                  this.form.ownId = "";
              }else if(value.value == "加工商"){
                  this.form.ownId = this.form.deptId;
              }
          }
          this.findObject(this.option.column, 'ownId').display = value.value == "采购商";
      },
      deptIdChange(value){
          if(this.form.supType == "加工商"){
              this.form.ownId = value.value;
          }
          this.findObject(this.option.column, 'ownId').display = this.form.supType == "采购商";
      },
      setSupCode(value) {
          this.$refs.form.form.supCode = value.value.substring(0,4)
      },
    initData(tenantId) {
      // getDeptTree(tenantId).then(res => {
      //   const column = this.findObject(this.option.column, 'deptId');
      //   column.dicData = res.data.data;
      // });
        userCompany().then(res=>{
            if (res.data.success) {
                this.dept = res.data.data;
                if (!this.dept) {
                    // this.$message({
                    //     type: "error",
                    //     message: "用户无组织机构信息，请联系安伟工作人员！"
                    // });
                    return;
                } else {
                    this.isRole = this.dept.bodyType;
                    // if(this.isRole === 3){
                    //     this.findObject(this.option.column, 'deptId').display = false;
                    // }
                }
            }
        })
    },
    onSubmit(form, done) {
      this.btnLoading = true;
      update(form).then(res => {
        if (res.data.success) {
          this.$message({
            type: "success",
            message: res.msg || "保存成功!"
          });
          setTimeout(() => {
              this.btnLoading = false;
              done();
            this.$refs.modal_1.hide();
          }, 1000)
        } else {
          this.$message({
            type: "error",
            message: res.msg || "保存失败!"
          });
        }
      }).catch(err => {
        console.log(err)
        done();
        this.btnLoading = false;
      })
    },
    show(option) {
      if (option.id) {
        setTimeout(() => {
          getDetail(option.id).then(res => {
            if (res.data.success) {
              this.form = res.data.data;
              // this.form.taxRate = Number(this.form.taxRate)
              this.findObject(this.option.column, 'createUserName').display = true;
              this.findObject(this.option.column, 'createTime').display = true;
              this.findObject(this.option.column, 'ownId').display = this.form.supType == "采购商";
              // this.findObject(this.option.column, 'deptId').disabled = this.isRole === 3 && this.form.supType === "加工商";
            }
          })
        }, 500);
      } else {
        this.form = {}
        this.findObject(this.option.column, 'createUserName').display = false;
        this.findObject(this.option.column, 'createTime').display = false;
        // this.findObject(this.option.column, 'deptId').disabled = false;
      }
      if(this.isRole === 3){//加工商
          this.form.supType = "采购商";
          this.form.ownId = this.dept.id;
          this.findObject(this.option.column, 'supType').disabled = true;
          this.findObject(this.option.column, 'ownId').disabled = true;
      }
      this.title = option.title;
      this.type = option.type;
      this.option.detail = this.type === "view";
      this.editable = this.type !== "view";
      this.$refs.modal_1.show();
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    opened() {
      console.log("opened")
    },
    closed() {
      this.$emit("success");
    }
  }
};
</script>

<style></style>
